package io.lkt.modules.sys.wechat.handler;

import com.tulele.vtool.model.PlatformSysInfo;
import io.lkt.common.utils.DateUtil;
import io.lkt.common.utils.R;
import io.lkt.modules.sys.entity.BArticleInfoEntity;
import io.lkt.modules.sys.entity.BBrandInfoEntity;
import io.lkt.modules.sys.entity.BUserGroupOpenidEntity;
import io.lkt.modules.sys.entity.BUserInfoEntity;
import io.lkt.modules.sys.service.*;
import io.lkt.modules.sys.wechat.service.WeixinServiceDL;
import io.lkt.modules.sys.wechat.service.WeixinServiceMap;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * 发送模板消息
 */
@RequestMapping("/message")
@RestController
@Slf4j
public class TemplateMessageHandler {
    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private BUserInfoService bUserInfoService;

    @Autowired
    private BUserGroupOpenidService bUserGroupOpenidService;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private BUserBrandInfoService bUserBrandInfoService;

    @Autowired
    private BArticleInfoService bArticleInfoService;

    @PostMapping(value = "/sendZWAMessage/{userId}", produces = "application/json;charset=UTF-8")
    public R sendZWAMessage(@PathVariable("userId") Integer userId) throws Exception {

        // 获取用户的第一个品牌
        BBrandInfoEntity brandInfo = bUserBrandInfoService.getUserLatestBrandInfo(userId);

        // 获取用户该品牌下最新的一篇文章
        BArticleInfoEntity articleInfo = bArticleInfoService.getLatestArticleByBranbId(brandInfo.getId());

        if (Objects.isNull(brandInfo)) return R.error("用户没有订阅品牌");
        if (!Objects.isNull(brandInfo) && Objects.isNull(articleInfo)) return R.error("用户的品牌没有文章");

        BUserInfoEntity userInfo = bUserInfoService.queryUserInfo(userId);
        String gzhCode = userInfo.getGzhCode();

        BUserGroupOpenidEntity ugoId = bUserGroupOpenidService.getUserOpenId(gzhCode, userInfo.getUserId());
        if (ugoId != null) {
            userInfo.setOpenId(ugoId.getOpenId());
        }

        PlatformSysInfo sysGzh = sysGzhService.getPlatformSysInfo(gzhCode);

        // 获取当前日期
        String currentDate = new SimpleDateFormat("yyyy年MM月dd日").format(DateUtil.getCurDate());

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(userInfo.getOpenId())
                // 模板id
                .templateId(sysGzh.getSysGzh().getMakeInventoryTempId())
                // 模板跳转链接
                .url(sysGzh.getFrontDomain() + "pages/article/detail.html?articleId=" + articleInfo.getId() + "&userId=" + userId)
                .build();
        String firstMsg1 = "您好，您的获客工具尚未激活，完成以下步骤哦！";
        String keyword1Msg = "点击查看（" + brandInfo.getBrandName() + "）好文";
        String remarkMsg1 = "点击上方蓝字，查阅使用文章哦~\n" +
                "回复“6”，添加老师【一对一】教你使用";
        // 添加模板数据
        templateMessage.addData(new WxMpTemplateData("first", firstMsg1, "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", keyword1Msg, "#532C38"))
                .addData(new WxMpTemplateData("keyword2", articleInfo.getArticleTitle(), "#4B8284"))
                .addData(new WxMpTemplateData("keyword3", currentDate, "#FF0000"))
                .addData(new WxMpTemplateData("remark", remarkMsg1, "#0000FF"));

        try {
            // 发送模板消息
            WeixinServiceDL weixinService = WeixinServiceMap.getWeixinService(gzhCode);
            if (weixinService == null) {
                weixinService = objectFactory.getObject();
                weixinService.reSetConfigStorage(gzhCode);
                WeixinServiceMap.putWeixinService(gzhCode, weixinService);
            }
            weixinService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
//            e.printStackTrace();
            return R.error("发送失败");
        }

        return R.ok();
    }
}
